package resp

import (
	"context"
	"github.com/gin-gonic/gin"
	"net/http"
)

type Result struct {
	Ctx  *gin.Context
	Code int
	Msg  string
	Data interface{}
}

func (r Result) M(message string) Result {
	r.Msg = message
	return r
}

func (r Result) DataEmpty(prefix ...string) Result {
	r.Msg = "数据不存在"
	if len(prefix) != 0 {
		r.Msg = prefix[0] + "不存在"
	}
	return r
}

func (r Result) result() map[string]interface{} {
	data := map[string]interface{}{
		"success": r.Code,
		"msg":     r.Msg,
		"data":    r.Data,
	}
	if traceId := r.Trace(); traceId != "" {
		data["trace_id"] = traceId
	}
	return data
}

func (r Result) Success(data ...interface{}) {
	r.Code = Success

	if r.Msg == "" {
		r.Msg = getMessageErr(Success)
	}

	if data == nil {
		r.Data = make(map[string]interface{})
	} else {
		r.Data = data[0]
	}
	r.Ctx.JSON(http.StatusOK, r.result())
}

func (r Result) Fail(data ...interface{}) {
	r.Code = Fail

	if r.Msg == "" {
		r.Msg = getMessageErr(Fail)
	}

	if data == nil {
		r.Data = make(map[string]interface{})
	} else {
		r.Data = data[0]
	}
	r.Ctx.JSON(http.StatusOK, r.result())
}

func (r Result) Trace() string {
	ctxTrace, ok := r.Ctx.Get("ctx")
	var traceId string
	if ok {
		traceId = ctxTrace.(context.Context).Value("trace_id").(string)
	}
	return traceId
}

func SetPanic(message string) string {
	return PanicTarget() + message
}

func GetPanic(message string) string {
	return message[7:]
}

func PanicTarget() string {
	return "manual:"
}
